<template>
	<view class="page">
		<!-- :keyheight="screenHeight-keyheight-80" -->
		<view class="head-block" @click="handClick()">
			<ChatInterfaceNavigation :nickName="friendInfo.nickName" 
			:receiverStatus = "friendInfo.status"
			></ChatInterfaceNavigation>
		</view>
		<!-- screenHeight-keyheight-rpxToPx(200)-80 -->
		<view class="message-list-block"
		@click="hideKeyHeight"
		:style="{
			'margin-top':90+'px',
			'height': screenHeight-keyheight-rpxToPx(200)-80+'px',
		}">
		<!-- {{keyboardHeightFlg}}-{{keyheight}}-{{iconFunctionTyp}} -->
			<scroll-view class="scroll-Y"
			scroll-y="true"
			refresher-enabled
			@refresherrefresh = showMoreMsg
			:refresher-triggered = isRefresher
			refresher-background= "#efefef"
			style="height: 100%;width: 100%;"
			:scroll-top="scrollTop"
			:scroll-into-view="scrollTo" scroll-with-animation="true" >
				<view v-for="(mg,index) in messageList" :key=index :id="'id'+index" :class="'index'+index">
					<!-- {{scrollTo}}---{{'id'+index}} -->
					<send-message v-if="mg.sender == userInfo.id" :msg="mg" :pic="userInfo.headPic"
					></send-message>
					<receive-message v-else :msg="mg" :pic="friendInfo.headPic">
					</receive-message>
				</view>
			</scroll-view>
		</view>
		
		
		<view class="main-block" >
			
			<view class="send-block">
				<!-- auto-height -->
				<view class="send-input-block">
					<textarea v-model="msg.context"
						ref="textareaRef"
						:autoFocus="true" 
						class="send-input" 
						:adjust-position="false"
						cursor-spacing="45"
						:focus="isFocus"
						@focus="textareaFocus"
						@blur="textareaBlur" 
						@linechange="texTlinechange" 
						auto-height
						style="max-height: 200rpx;width: 100%; overflow: auto;"
						type="text" 
						@confirm="send"
						confirm-type="send"/>
				</view>
				<view class="">
					<!--  @touchend.prevent="clickRequest('text')" -->
					<button class="send-button" :disabled="msg.context == ''" @touchend.prevent="send">发送</button>
				</view>
				
			</view>
			
			
			
			<view class="function-menu">
				<label class="iconfont iconyuyin" @click="choiceVioce"></label>
				<label class="iconfont iconxiangce" @click="choicePhoto()"></label>
				<label class="iconfont iconxiangji1" @click="choiceCamera()"></label>
				<label class="iconfont iconhongbao"></label>
				<label class="iconfont iconxiaolian1" @click="choiceEmoj"></label>
				<label class="iconfont icontianjia"></label>
			</view>
			
		
			<!-- 普通占位 -->
			<view 
			v-if="iconFunctionTyp == ''"
			class="common-block"
			:style="{
				'height':keyboardHeightFlg ? (keyheight - deviceBottom)+'px' : '0px'
			}">
				
			</view>
			
			
			<!-- 语音占位 -->
			<view 
			v-if="iconFunctionTyp == 'vioce'"
			class="vioce-block"
			:style="{
				'height':keyboardHeightFlg ? (keyheight - deviceBottom)+'px' : '0px'
			}">
				<swiper 
				@change="swiperChange"
				:current="currentVioceIndex"
				class="voice-swiper-top">
					<!-- 语音输入上滑块 -->
					<swiper-item  v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">按住变声</view>
					</swiper-item>
					<swiper-item v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">按住说话</view>
					</swiper-item>
					<swiper-item v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">点击录音</view>
					</swiper-item>
				</swiper>
				<swiper 
				@change="swiperChange"
				:current="currentVioceIndex"
				class="voice-swiper-centre">
					<!-- 语音输入中滑块 -->
					<swiper-item  
					style="background-color: #aaff00;"
					v-if="iconFunctionTyp == 'vioce'"
					>
						<view class="swiper-item">变声</view>
					</swiper-item>
					<swiper-item 
					style="background-color: #55aaff;"
					v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">对讲</view>
					</swiper-item>
					<swiper-item 
					style="background-color: #ff0000;"
					@touchstart="touchstartVoice"
					@touchmove.stop.prevent="touchmoveVoice" 
					@touchend="touchendVoice"
					@touchcancel="touchcancelVoice"
					v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">录音</view>
					</swiper-item>
				</swiper>
				
				<swiper 
				disable-touch
				class="voice-swiper-bottom" 
				:current="currentVioceIndex"
				:display-multiple-items="5">
					<!-- 语音输入下滑块 -->
					<swiper-item  v-if="iconFunctionTyp == 'vioce'">
					</swiper-item>
					<swiper-item  v-if="iconFunctionTyp == 'vioce'">
					</swiper-item>
					<swiper-item  
					:style="{'color':currentVioceIndex == 0 ? '#272727': ''}"
					v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">变声</view>
					</swiper-item>
					<swiper-item 
					:style="{'color':currentVioceIndex == 1 ? '#272727': ''}"
					v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">对讲</view>
					</swiper-item>
					<swiper-item 
					:style="{'color':currentVioceIndex == 2 ? '#272727': ''}"
					v-if="iconFunctionTyp == 'vioce'">
						<view class="swiper-item">录音</view>
					</swiper-item>
					<swiper-item  v-if="iconFunctionTyp == 'vioce'">
					</swiper-item>
					<swiper-item  v-if="iconFunctionTyp == 'vioce'">
					</swiper-item>
				</swiper>
			</view>
			
			<!-- 表情占位 -->
			<view 
			v-if="iconFunctionTyp == 'emoji'"
			class="emoji-block"
			:style="{
				'height':keyboardHeightFlg ? (keyheight - deviceBottom)+'px' : '0px'
			}">
			<!-- 表情列表 -->
				<swiper class="swiper-emoji-item">
					<swiper-item>
						<scroll-view scroll-y="true" class="scroll-emoji">
							<block v-for="(item,index) in emojiList" :key="index">
								<text @click="setEmoj(item,index)" class="emoj_box_img">{{item}}</text>
							</block>
						</scroll-view>
					</swiper-item>
					<swiper-item>
						<scroll-view scroll-y="true" class="scroll-emoji">
							<block v-for="(item,index) in emojiList" :key="index">
								<text @click="setEmoj(item,index)" class="emoj_box_img">{{item}}</text>
							</block>
						</scroll-view>
					</swiper-item>
				</swiper>
				<!-- 表情菜单 -->
				<!-- <view class="swiper-emoji-menu">
					<view class="emoji-function-more">
						<label class="iconfont iconfengzheng"></label>
					</view>
					<swiper 
					class="swiper-emoji-menu-swiper"
					display-multiple-items=6
					>
						<swiper-item  v-for="i in emojiList.length">
							<view class="swiper-emoji-menu-item">
								{{i}}
							</view> 
						</swiper-item>
					</swiper>
				</view> -->
			</view>
			
		</view>
		
		<!-- 语音状态显示 -->
		<template v-if="voiceFlg">
			<div class="voice_bd">
				<div class="voice_ui">
					<image class="voice_ui_img" src="@/static/temp/luyinqi.png" ></image>
					<text class="voice_ui_text">{{voiceTis}}</text>
				</div>
			</div>
		</template>
		
	</view>
	
</template>

<script>
	import ChatInterfaceNavigation from '@/components/my-components/navigation/chat-interface-navigation.nvue'
	import store from '@/store/index.js'
	import toolBox from "./components/tool.vue"
	import emojiBox from "./components/emoj.vue"
	import emoji from './mixins/emoji.js'
	import friend from "@/api/friend.js"
	import message from "@/api/message.js"
	import user from "@/api/user.js"
	
	var _self
	
	const recorderManager = uni.getRecorderManager(); //全局录音管理器

	export default {
		data() {
			return {
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight, //获取的状态栏高度
				screenHeight: uni.getSystemInfoSync().screenHeight, // 手机屏幕高度
				screenWidth: uni.getSystemInfoSync().screenWidth, // 手机屏幕宽度
				lastTapTimeoutFunc:null,
				lastTapDiffTime:0,
				userInfo: {}, //用户数据
				friendInfo: {}, // 好友数据
				msg: this.utils.message,
				keyheight: 0, // 键盘弹起高度
				cursorSpacing: 45 , // 输入框距离键盘的高度 
				scrollTop: 0,
				scrollTo: '',
				isFocus: false,
				old: {
					scrollTop: 0
				},
				messageList: [],
				isRefresher: false, // 是否下拉标识
				deviceBottom: 0, // 底部安全区域高度
				keyboardHeightFlg: false ,// 当前是否有键盘占位标志
				iconFunctionTyp: "", //当前选中的图标功能类型
				lineCount: 1 ,//输入框行数 最多6行
				currentVioceIndex: 1, // 当前语音滑块下标
				currentVioceColor: '' ,// 当前语音滑块颜色
				emojiList: [] ,// 表情列表
				isVoice: false,
				voiceText: '按住 说话',
				voiceTis: "手指上滑 取消发送",
				voiceFlg: false,
				voiceStop: false,
				voiceTimer: null,
				voiceLength: 0,
				voicePageY: 0,
			}
		},
		async onLoad(data) {
			_self = this
			uni.hideTabBar()
			// let iosObj = uni.getSystemInfoSync().getSafeAreaInsets()
			// // 获取底部安全区域高度 兼容苹果X 以上机型 
			// _self.deviceBottom = iosObj.deviceBottom || 0
			
			// 获取表情列表
			_self.emojiList = emoji
			
			// 获取用户数据
			var info = uni.getStorageSync("userInfo")
			if(info == ""){
				// 关闭所有页面跳转登录页面 同时关闭定时任务
				uni.reLaunch({
					url:'../../login/addAndRegister/addAndRegister',
					animationType: 'pop-in',
					animationDuration: 200
				})
			}else{
				_self.userInfo = info
			}
			
			// 默认是文本内容
			_self.msg.type = 1

			
			
			// 获取好友资料
			_self.friendInfo = await friend.getFriendInfo(data.receiver)
			
			// 设置当前聊天窗口位置
			this.$store.commit("setMessageLocation",_self.friendInfo.id)
			
			
			// 获取当前好友的所有消息
			var moreMsg = await message.getMessageByFriend(_self.friendInfo.id,_self.messageList.length)
			_self.messageList = Object.assign(moreMsg,_self.messageList)
			
			// 监听键盘高度变化
			uni.onKeyboardHeightChange(res => {
				if(_self.iconFunctionTyp == "" || _self.iconFunctionTyp == "photo" || _self.iconFunctionTyp == "camera"){
					_self.keyheight = res.height
					// 消息滑动
					_self.goButtom()
				}
			})
			
			uni.$on('updateChat',function(data){
				console.log('监听到事件来自 updateChat');
				// 获取当前好友的所有消息
				setTimeout(async function(){
					_self.messageList.push(data)
					_self.goButtom()
				},0)
				
			})
			
			_self.goButtom()
			
			// 创建全局录音监听
			this.onRecorderManager()
			
		},
		onShow() {
			// this.goButtom()
		},
		beforeDestroy() {
		},
		// 下拉刷新触发
		onPullDownRefresh() {
			// 停止当前页面下拉刷新
			uni.stopPullDownRefresh()
		},
		methods: { 
			// 创建全局录音监听
			onRecorderManager() {
				//录音开始
				recorderManager.onStart((e) => {
					console.log('录音开始')
				})
				// 录音报错
				recorderManager.onError((e) => {
					console.log(e)
					console.log('录音报错')
				})
				//录音结束
				recorderManager.onStop((e) => {
					console.log('录音结束')
					if (_self.voiceStop) {
						uni.showToast({
							icon: "none",
							title: "取消发送"
						})
					} else {
						if (this.voiceLength < 1) {
							uni.showToast({
								icon: "none",
								title: "发送时间过短"
							})
						} else {
							console.log('发送语音')
							console.log(e)
							var uploadTask = uni.uploadFile({
								url: _self.utils.uploadUrl,
								filePath: e.tempFilePath,
								name: 'file',
								formData: {},
								success: (uploadFileRes) => {
									// 添加语音
									_self.msg.context = uploadFileRes.data
									_self.$nextTick(function(){
										_self.msg.type = 2
										_self.send()
									})
								},
								fail:(res)=>{
									console.log(res)
								}
							});
							
							// uploadTask.onProgressUpdate((res) => {
							// 	console.log('上传进度' + res.progress);
							// 	console.log('已经上传的数据长度' + res.totalBytesSent);
							// 	console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
							// })
							
							// this.addMsg('', 2, e.tempFilePath, this.voiceLength)
							// this.$nextTick(() => {
							// 	this.voiceLength = 0
							// })
						}
					}
				})
			},
			// 检测录音时间
			isVoiceTime() {
				if (this.voiceLength < 1) {
					uni.showToast({
						icon: "none",
						title: "发送时间过短"
					})
				} else {
					this.voiceLength = 0
				}
			},
			// 按下录音触发
			touchstartVoice(e) {
				this.voicePageY = (e.changedTouches[0].pageY).toFixed(2)
				this.voiceText = '松开 结束'
				this.voiceFlg = true
				recorderManager.start({
					format: "mp3"
				}); //录音开始,
				this.voiceTimer = setInterval(() => {
					this.voiceLength += 0.1
					// console.log(this.voiceLength.toFixed(1))
				}, 100)
				console.log('touchstartVoice', this.voicePageY)
			},
			// 滑动录音触发
			touchmoveVoice(e) {
				let numTemp = this.voicePageY - ((e.changedTouches[0].pageY).toFixed(2))
				if (numTemp >= 60) {
					// console.log('取消发送')
					this.voiceStop = true
					this.voiceTis = "松开手指 取消发送"
				} else {
					// console.log('继续发送')
					this.voiceStop = false
					this.voiceTis = "手指上滑 取消发送"
				}
			},
			// 松开录音触发
			touchendVoice() {
				this.voiceFlg = false
				this.voiceText = '按住 说话'
				this.voiceTis = "手指上滑 取消发送"
				console.log('touchendVoice')
				console.log(this.voiceStop)
				clearInterval(this.voiceTimer);
				this.voiceTimer = null
			
				recorderManager.stop(); //录音结束
			},
			// 打断录音触发
			touchcancelVoice() {
				clearInterval(this.voiceTimer);
				this.voiceTimer = null
				this.voiceFlg = false
				this.voiceText = '按住 说话'
				this.voiceTis = "手指上滑 取消发送"
				console.log('touchcancelVoice')
				recorderManager.stop(); //录音结束
			},
			// 隐藏键盘高度占位
			hideKeyHeight(){
				// 收起键盘占位高度
				this.keyheight = 0
				this.keyboardHeightFlg = false
				this.iconFunctionTyp = ""
				this.isFocus = false
				uni.hideKeyboard()
			},
			// 添加表情
			setEmoj(item, index) {
				console.log(item, index)
				this.msg.context += item
			},
			// 点击表情触发
			choiceEmoj(i) {
				if(_self.iconFunctionTyp != 'emoji'){
					// 第一次点击
					_self.iconFunctionTyp = 'emoji'
					_self.keyboardHeightFlg = true
					_self.keyheight = 307
					uni.hideKeyboard()
				}else{
					// 再次点击 收起键盘
					_self.iconFunctionTyp = ""
					_self.keyboardHeightFlg = false
					_self.keyheight = 0
					_self.isFocus = false
					uni.hideKeyboard()
				}
				this.goButtom()
			},
			// 点击相机触发
			choiceCamera(){
				_self.iconFunctionTyp = 'camera'
				uni.chooseImage({
				    count: 6, //默认9
				    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['camera'], //从相册选择
				    success: function (res) {
						const tempFilePaths = res.tempFilePaths;
						var uploadTask = uni.uploadFile({
							url: _self.utils.uploadUrl,
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {},
							success: (uploadFileRes) => {
								_self.msg.context = uploadFileRes.data
								_self.$nextTick(function(){
									_self.msg.type = 4
									_self.send()
								})
							},
							fail:(res)=>{
								console.log(res)
							}
						});
						
						// uploadTask.onProgressUpdate((res) => {
						// 	console.log('上传进度' + res.progress);
						// 	console.log('已经上传的数据长度' + res.totalBytesSent);
						// 	console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
						// })
				    }
				});
				
				// 收起键盘占位高度
				this.keyheight = 0
				this.keyboardHeightFlg = false
				_self.isFocus = false
				uni.hideKeyboard()
			},
			// 点击图片触发
			choicePhoto(){
				_self.iconFunctionTyp = 'photo'
				uni.chooseImage({
				    count: 6, //默认9
				    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['album'], //从相册选择
				    success: function (res) {
						const tempFilePaths = res.tempFilePaths;
						var uploadTask = uni.uploadFile({
							url: _self.utils.uploadUrl,
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {},
							success: (uploadFileRes) => {
								// 添加消息
								_self.msg.context = uploadFileRes.data
								_self.$nextTick(function(){
									// 修改消息状态
									_self.msg.type = 4
									// 发送
									_self.send()
								})
							},
							fail:(res)=>{
								console.log(res)
							}
						});
						
						// uploadTask.onProgressUpdate((res) => {
						// 	console.log('上传进度' + res.progress);
						// 	console.log('已经上传的数据长度' + res.totalBytesSent);
						// 	console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
						// })
				    }
				});
				
				// 收起键盘占位高度
				this.keyheight = 0
				this.keyboardHeightFlg = false
				_self.isFocus = false
				uni.hideKeyboard()
			},
			// 点击语音icon
			choiceVioce(){
				if(_self.iconFunctionTyp == ""){
					// 第一次点击 隐藏键盘
					_self.iconFunctionTyp = "vioce"
					_self.keyboardHeightFlg = true
					_self.keyheight = 307
					uni.hideKeyboard()
				}else if(_self.iconFunctionTyp == "vioce"){
					// 第二次点击 收起
					_self.iconFunctionTyp = ""
					_self.keyboardHeightFlg = false
					_self.isFocus = false
					_self.keyheight = 0
					uni.hideKeyboard()
				}else{
					// 其他标签转过来的 同第一次
					_self.iconFunctionTyp = "vioce"
					_self.keyboardHeightFlg = true
					_self.keyheight = 307
					uni.hideKeyboard()
				}
				
				this.goButtom()
			},
			// 语音滑块切换触发
			swiperChange(event){
				this.currentVioceIndex = event.detail.current
				
				// console.log(event.detail)
			},
			// 输入框获取焦点
			textareaFocus() {
				// 修改 输入框聚焦状态
				_self.keyboardHeightFlg = true
				this.iconFunctionTyp = ""
				
				// 修改消息类型
				_self.msg.type = 1
				
				// 触发滚动到页面底部
				this.goButtom()
			},
			// 失去焦点触发
			textareaBlur() {
				if (this.clickEvent !== '') {
					// 点击 功能键 不触发 功能栏的收起
				} else {
					// 焦点消失 修改输入框位置
					_self.keyboardHeightFlg = false
				}
				this.$nextTick(() => {
					// this.clickEvent = ''
					// 修改 输入框聚焦状态
					// this.textareaFocusFlg = false
				})
			},
			// 输入框行高变化
			texTlinechange(e) {
				// 获取行高
				this.lineCount = e.detail.lineCount
				// this.$nextTick(function(){
				// 	this.goButtom()
				// })
			},
			// 返回上一级
			toBack() {
				uni.navigateBack({
					delta:1,
					animationType: 'pop-out',
					animationDuration: 200
				})
			},
			// rpx 转 px
			rpxToPx(rpx){
				return uni.upx2px(rpx)
			},
			// px转rpx
			pxToRpx(px){
				var lence = this.screenWidth/750
				return lence * px
			},
			// 键盘聚焦事件
			keyFoucus(e){
				console.log(e.detail.height)
			},
			// 键盘高度事件
			keyboardheightchange(event){
				// 消息滑动
				this.goButtom()
				console.log(event.detail.height)
			},
			// 单击或双击
			handClick() {
				let _this = this;
				let curTime = new Date().getTime();
				let lastTime = _this.lastTapDiffTime;
				_this.lastTapDiffTime = curTime;
				//两次点击间隔小于300ms, 认为是双击
				let diff = curTime - lastTime;
				if (diff < 300) {
					// console.log("双击")
					this.goTop()
					clearTimeout(_this.lastTapTimeoutFunc); // 成功触发双击事件时，取消单击事件的执行
				} else {
					// 单击事件延时300毫秒执行
					_this.lastTapTimeoutFunc = setTimeout(function() {
						// console.log("单击")
						// this.goTop()
						//_this.handleVideo('playOrStop',index)自定义事件
					}, 300);
				}
			},
			upper: function(e) {
				// console.log(e)
			},
			lower: function(e) {
				// console.log(e)
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				// uni.showToast({
				// 	icon:"none",
				// 	title:"纵向滚动 scrollTop 值已被修改为 0"
				// })
			},
			// 跳转到底部
			goButtom: function(e) {
				this.scrollTo = ''
				setTimeout(function(){
					if(_self.messageList.length > 0){
						_self.$nextTick(function(){
							_self.scrollTo = 'id'+ (_self.messageList.length-1)
							// _self.scrollTop = 99999
						})
					}
				},500)
				
			},
			// 发送消息
			async send() {
				if(_self.msg.context == ''){
					return
				}
				
				_self.msg.sender = _self.userInfo.id
				_self.msg.receiver = _self.friendInfo.id
				_self.msg.label = _self.messageList.length
				
				// 深拷贝
				var copeMsg = JSON.stringify(_self.msg);
				var sendMsg = JSON.parse(copeMsg);
				
				this.$nextTick(function(){
					_self.messageList.push(sendMsg)
				})
				
				_self.msg.context = ''
				
				// 滚动到底部
				this.goButtom()
				
				// 发送回执
				var sendResult = await message.sendMessage(sendMsg)
				
				// 更新发送成功信息状态
				for (var i = 0; i < _self.messageList.length; i++) {
					if(_self.messageList[i].label === sendResult){
						_self.messageList[i].status = 1
					}
				}
				
				// 持久化消息到本地
				var storageMsgList = uni.getStorageSync("messageList")
				if(storageMsgList === null || storageMsgList === undefined || storageMsgList === ""){
					storageMsgList = {}
				}
				if(storageMsgList[_self.friendInfo.id] === null || storageMsgList[_self.friendInfo.id] === undefined || storageMsgList[_self.friendInfo.id] === ""){
					storageMsgList[_self.friendInfo.id] = {}
				}
				
				storageMsgList[_self.friendInfo.id]["read"] = _self.messageList
				
				uni.setStorageSync("messageList",storageMsgList)
				
			},
			async showMoreMsg(){
				_self.isRefresher = true
				var moreMsg = await message.getMessageByFriend(_self.friendInfo.id,_self.messageList.length)
				if(moreMsg === null || moreMsg === undefined || moreMsg.length === 0){
					uni.showToast({
						title: "没有更多消息了！",
						icon: "none",
						duration: 500
					});
				}else{
					_self.messageList = moreMsg.concat(_self.messageList)
				}
				this.$nextTick(function(){
					_self.isRefresher = false
				})
			}
			
		},
		components: {
			ChatInterfaceNavigation,
			toolBox,
			emojiBox
		}
	}
</script>

<style>
	@import url("chat.css");
</style>
